package models

import (
	"github.com/astaxie/beego/orm"
	"strconv"
	//"github.com/astaxie/beego"
	//"github.com/astaxie/beego"
)

//import "github.com/astaxie/beego/orm"

type PqTestCategory struct{
	CategoryNode
	Category
	PointData string
	PointSetting string
}
func (this *PqTestCategory) ListAll(q []interface{}) ([]orm.Params,interface{}) {
	var nodes []orm.Params
	model := GetSlaveDb()
	model.Raw("select SQL_CALC_FOUND_ROWS * from pq_test_category where state > ? order by level asc,ordering desc limit ?,?",q).Values(&nodes)
	//amount := GetTotal(model)
	var maps []orm.Params
	//o := GetSlaveDb()
	model.Raw("select count(*) as amount from pq_test_category where state > -1").Values(&maps)
	return nodes,maps[0]["amount"]
}

func (this *PqTestCategory) ReGenerateTestCategory(){
	slave := GetSlaveDb()
	master:= GetMasterDb()
	var root PqTestCategory
	slave.QueryTable("pq_test_category").Filter("id",1).One(&root)
	root.Lft = 1
	root.Rgt = 2
	master.Update(&root)
	this.ReGenerateChilds(root.Id)
}

func (this PqTestCategory) ReGenerateChilds(pid interface{})  {
	var nodes []orm.Params
	slave := GetSlaveDb()
	slave.Raw("select * from pq_test_category where pid=? and state > -1",pid).Values(&nodes)
	for _,v := range nodes{
		this.ReGenerateNode(v["id"])
		this.ReGenerateChilds(v["id"])
	}
}

func (this PqTestCategory)ReGenerateNode(id interface{}){
	slave := GetSlaveDb()
	master:= GetMasterDb()
	var node PqTestCategory
	var parent PqTestCategory
	slave.QueryTable("pq_test_category").Filter("id",id).One(&node)
	slave.QueryTable("pq_test_category").Filter("id",node.Pid).One(&parent)
	var nodes []orm.Params
	slave.Raw("select * from pq_test_category where rgt > ? and state > -1",parent.Rgt).Values(&nodes)
	//beego.Warning(nodes)
	for _,v := range nodes{
		//beego.Warning(nodes)
		rgt,_ := strconv.Atoi(v["rgt"].(string))
		lft,_ := strconv.Atoi(v["lft"].(string))
		level,_ := strconv.Atoi(v["level"].(string))
		up := orm.Params{
			"rgt" : rgt + 2,
		}
		if level >= parent.Level {
			up["lft"] = lft + 2
		}
		//beego.Warning(up)
		master.QueryTable("pq_test_category").Filter("id",v["id"]).Update(up)
	}
	node.Lft = parent.Rgt
	node.Rgt = parent.Rgt + 1
	master.Update(&node)

	parent.Rgt = parent.Rgt + 2
	master.Update(&parent)
}
